package com.kehutong.wwin.service.service;

import com.kehutong.common.util.Token;
import com.kehutong.wwin.service.entity.DepartmentMap;
import com.kehutong.wwin.service.util.WwInHttpClient;
import com.kehutong.wxapi.request.*;
import com.kehutong.wxapi.response.BatchGetByUserResponse;
import com.kehutong.wxapi.response.DepartmentListResponse;
import com.kehutong.wxapi.response.FollowUserListResponse;
import com.kehutong.wxapi.response.UserListResponse;
import com.kehutong.wxapi.service.DepartmentService;
import com.kehutong.wxapi.service.ExternalContactService;
import com.kehutong.wxapi.service.UserService;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.List;

/**
 * 向企业微信发送
 *
 * @author liuzhen(liuxing521a@163.com)
 * @createTime 2020年7月20日下午6:16:25
 */
@WebService("/wwin/department/wwin")
public class ToWwinDepartmentService {
	private static final Logger logger= LoggerFactory.getLogger(ToWwinDepartmentService.class);

	@Inject
	private WwInHttpClient httpClient;
	@Inject
	private JdbcSession jdbcSession;

	@Inject
	private DepartmentService departmentService;

    @Inject
	private UserService userService;

	@Inject
	private ExternalContactService externalContactService;

	@ReqMapping("/create")
	public Object wwCreate(Token token, JSONObject khtJson) throws Exception {
		DepartmentMap map = createDepartment(khtJson);
		String oldId=map.getKhtid();
		JSONObject rs = httpClient.postWWin("/cgi-bin/department/create", token, true, http->{
			JSONObject json = map.toWwJson();
			json.remove("id");
			http.setBody(json.toJSONString());
		});
		
		int result = rs.getIntValue("errcode");
		if (result != 0) {
			return Result.error(result, rs.getString("errmsg"));
		}

		map.setId(rs.getString("id"));
		String newKhtId=ToKhtDepartmentService.toKhtId(token.getCompanyNo(),map.getId());
		map.setKhtid(newKhtId);


		JSONObject updateResult = httpClient.postKht("/basic/department/service/updateIdByInner", token, http-> {
			http.addParam("oldId",oldId);
			http.addParam("newId",newKhtId);
		});
		jdbcSession.insert(map);
		return Result.success();
	}
	
	@ReqMapping("/update")
	public Object wwUpdate(Token token, JSONObject khtJson) throws Exception {
		DepartmentMap map = getDepartment(khtJson);
		JSONObject rs = httpClient.postWWin("/cgi-bin/department/update", token, true, http->{
			http.setBody(map.toWwJson().toJSONString());
		});
		
		int result = rs.getIntValue("errcode");
		if (result != 0) {
			return Result.error(result, rs.getString("errmsg"));
		}

		return Result.success();
	}
	
	@ReqMapping("/delete")
	public Object wwDelete(Token token, JSONObject khtJson) throws Exception {
		DepartmentMap map = getDepartment(khtJson);
		JSONObject rs = httpClient.postWWin("/cgi-bin/department/delete", token, true, http->{
			http.addParam("id", map.getId());
		});
		
		int result = rs.getIntValue("errcode");
		if (result != 0) {
			return Result.error(result, rs.getString("errmsg"));
		}
		
		jdbcSession.deleteById(map);
		return Result.success();
	}

	public JSONObject listDepartment(Token token) throws Exception {
		return httpClient.getWWin("/cgi-bin/department/list", token, true, http->{});
	}
	
	public JSONArray toWwId(JSONArray khtJsonArray) {
		JSONArray wwJsonArray = new JSONArray(khtJsonArray.size());
		for (int i  = 0; i < khtJsonArray.size(); i ++) {
			wwJsonArray.add(toWwId(khtJsonArray.getString(i)));
		}
		
		return wwJsonArray;
	}
	
	public String toWwId(String khtId) {
		DepartmentMap map = getDepartmentByKhtId(khtId);
		return map.getId();
	}
	
	public DepartmentMap getDepartmentByKhtId(String khtId) {
		return jdbcSession.findOne(DepartmentMap.class)
				.eq("khtid", khtId)
				.exe();
	}
	
	private DepartmentMap createDepartment(JSONObject khtJson) {
		DepartmentMap department = Pool.newInstance(DepartmentMap.class);
		department.setKhtid(khtJson.getString("id"));
		department.setName(khtJson.getString("name"));
		department.setSort(khtJson.getIntValue("sort"));
		
		String pid = khtJson.getString("parent_id");
		if (Objects.isEmpty(pid)) {
			department.setPid("0");
		} else {
			DepartmentMap parent = getDepartmentByKhtId(pid);
			department.setPid(parent.getId());
		}
		
		return department;
	}
	
	private DepartmentMap getDepartment(JSONObject khtJson) {
		DepartmentMap department = getDepartmentByKhtId(khtJson.getString("id"));
		
		department.setName(khtJson.getString("name"));
		department.setSort(khtJson.getIntValue("sort"));
		
		String pid = khtJson.getString("parent_id");
		if (Objects.isEmpty(pid)) {
			department.setPid("0");
		} else {
			DepartmentMap parent = getDepartmentByKhtId(pid);
			department.setPid(parent.getId());
		}
		
		return department;
	}
}
